package org.example.new_hbps_backend_reconstruction.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.new_hbps_backend_reconstruction.common.results.R;
import org.example.new_hbps_backend_reconstruction.mapper.SleepLogsMapper;
import org.example.new_hbps_backend_reconstruction.service.SleepLogsService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 丁利军
 * @date 2025年10月27日 11:29
 * @description TODO: 描述
 */

@Service
@RequiredArgsConstructor
@Slf4j
public class SleepLogsServiceImpl implements SleepLogsService {

    private final SleepLogsMapper sleepLogsMapper;

    @Override
    public R<?> getDailySleepSummary(Long patientUid, LocalDate date) {
        if (patientUid == null || date == null) {
            return R.failed("patientUid 与 date 均不能为空");
        }

        // 当天的起止时间范围
        LocalDateTime startTime = date.atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);

        SleepLogsMapper.SleepSummary summary = sleepLogsMapper.sumSleepByDate(patientUid, startTime, endTime);
        if (summary == null) {
            return R.ok(Map.of("sleepHours", 0, "sleepMinutes", 0), "无睡眠记录");
        }

        int totalMinutes = summary.getLightMinutes() + summary.getDeepMinutes();
        int hours = totalMinutes / 60;
        int minutes = totalMinutes % 60;

        Map<String, Object> data = new HashMap<>();
        data.put("sleepHours", hours);
        data.put("sleepMinutes", minutes);

        log.info("Sleep summary for uid={} on {} -> {}小时{}分钟", patientUid, date, hours, minutes);
        return R.ok(data, "查询成功");
    }
}
